<template>
  <div class="container">
    <header>
      <h1>Vue 2 + ECharts 折线图</h1>
      <p class="subtitle">Vue.js (2.6.12) + ECharts (5.4.0)</p>
    </header>
    
    <div class="controls">
      <button 
        class="btn" 
        :class="{active: chartType === 'basic'}" 
        @click="changeChartType('basic')"
      >
        <i class="fas fa-chart-line"></i> 基础折线图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'smooth'}" 
        @click="changeChartType('smooth')"
      >
        <i class="fas fa-wave-square"></i> 平滑折线图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'area'}" 
        @click="changeChartType('area')"
      >
        <i class="fas fa-mountain"></i> 区域面积图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'step'}" 
        @click="changeChartType('step')"
      >
        <i class="fas fa-layer-group"></i> 阶梯折线图
      </button>
    </div>
    
    <div class="charts-container">
      <!-- 主图表 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-chart-line"></i>
          </div>
          <h2 class="chart-title">{{ getChartTitle() }}</h2>
        </div>
        <div class="chart-wrapper" ref="lineChart"></div>
        
        <div class="data-controls">
          <h3>数据控制</h3>
          <div class="control-group">
            <label>
              数据点数量: {{ dataPoints }}
              <span class="range-value">{{ dataPoints }}</span>
            </label>
            <input type="range" min="5" max="30" v-model="dataPoints" @input="updateChartData">
          </div>
          
          <div class="control-group">
            <label>
              波动幅度: {{ volatility }}
              <span class="range-value">{{ volatility }}</span>
            </label>
            <input type="range" min="10" max="100" step="10" v-model="volatility" @input="updateChartData">
          </div>
          
          <div class="control-group">
            <label>
              起始值: {{ startValue }}
              <span class="range-value">{{ startValue }}</span>
            </label>
            <input type="range" min="100" max="500" step="50" v-model="startValue" @input="updateChartData">
          </div>
          
          <button class="btn" @click="refreshData">
            <i class="fas fa-random"></i> 生成随机数据
          </button>
        </div>
      </div>
      
      <!-- 数据表格 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-table"></i>
          </div>
          <h2 class="chart-title">数据详情</h2>
        </div>
        
        <div class="data-tabs">
          <button 
            v-for="(series, index) in chartSeries" 
            :key="index"
            class="tab-btn"
            :class="{active: activeTab === index}"
            @click="activeTab = index"
          >
            {{ series.name }}
          </button>
        </div>
        
        <table class="data-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>数值</th>
              <th>变化率</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(value, index) in activeSeriesData" :key="index">
              <td>{{ getTimeLabel(index) }}</td>
              <td>{{ value }}</td>
              <td>{{ calculateChangeRate(value, index) }}</td>
            </tr>
          </tbody>
        </table>
        
        <div class="data-controls">
          <h3>统计信息 - {{ chartSeries[activeTab] ? chartSeries[activeTab].name : '' }}</h3>
          <p><strong>当前数值:</strong> {{ currentValue }}</p>
          <p><strong>平均值:</strong> {{ averageValue }}</p>
          <p><strong>最大值:</strong> {{ maxValue }}</p>
          <p><strong>最小值:</strong> {{ minValue }}</p>
          <p><strong>总变化:</strong> {{ totalChange }}</p>
        </div>
      </div>
    </div>
    
    <footer>
      <p>Vue 2 + ECharts 折线图示例</p>
    </footer>
  </div>
</template>

<script>
// 引入ECharts
import * as echarts from 'echarts';

export default {
  name: 'LineChartDemo',
  
  data() {
    return {
      chartType: 'basic',
      dataPoints: 15,
      volatility: 50,
      startValue: 200,
      activeTab: 0,
      chartSeries: [],
      lineChartInstance: null
    }
  },
  
  computed: {
    // 当前激活系列的数据
    activeSeriesData() {
      return this.chartSeries[this.activeTab]?.data || [];
    },
    
    // 当前值
    currentValue() {
      const data = this.activeSeriesData;
      return data.length ? data[data.length - 1] : 0;
    },
    
    // 平均值
    averageValue() {
      const data = this.activeSeriesData;
      if (!data.length) return 0;
      const sum = data.reduce((total, value) => total + value, 0);
      return Math.round(sum / data.length);
    },
    
    // 最大值
    maxValue() {
      const data = this.activeSeriesData;
      return data.length ? Math.max(...data) : 0;
    },
    
    // 最小值
    minValue() {
      const data = this.activeSeriesData;
      return data.length ? Math.min(...data) : 0;
    },
    
    // 总变化
    totalChange() {
      const data = this.activeSeriesData;
      if (data.length < 2) return '0%';
      const change = ((data[data.length - 1] - data[0]) / data[0] * 100).toFixed(1);
      return change > 0 ? `+${change}%` : `${change}%`;
    }
  },
  
  methods: {
    // 生成时间标签
    getTimeLabel(index) {
      const baseTime = new Date(2023, 0, 1, 9);
      baseTime.setMinutes(baseTime.getMinutes() + index * 30);
      return baseTime.toTimeString().substring(0, 5);
    },
    
    // 生成单个系列的随机数据
    generateSingleSeriesData(baseValue) {
      const data = [baseValue];
      for (let i = 1; i < this.dataPoints; i++) {
        const change = (Math.random() - 0.5) * 2 * this.volatility;
        data.push(Math.max(50, Math.round(data[i - 1] + change)));
      }
      return data;
    },
    
    // 生成所有数据系列
    generateAllSeriesData() {
      const series = [
        {
          name: '销售额',
          data: this.generateSingleSeriesData(this.startValue),
          color: '#5470c6',
          symbol: 'circle',
          symbolSize: 8
        },
        {
          name: '用户数',
          data: this.generateSingleSeriesData(this.startValue * 0.8),
          color: '#91cc75',
          symbol: 'emptyCircle',
          symbolSize: 6
        },
        {
          name: '访问量',
          data: this.generateSingleSeriesData(this.startValue * 1.2),
          color: '#fac858',
          symbol: 'rect',
          symbolSize: 7
        }
      ];
      
      return series;
    },
    
    // 计算变化率
    calculateChangeRate(value, index) {
      if (index === 0) return '-';
      const prevValue = this.activeSeriesData[index - 1];
      const change = ((value - prevValue) / prevValue * 100).toFixed(1);
      return change > 0 ? `+${change}%` : `${change}%`;
    },
    
    // 更新图表数据
    updateChartData() {
      this.chartSeries = this.generateAllSeriesData();
      this.initLineChart();
    },
    
    // 刷新数据（重命名避免冲突）
    refreshData() {
      this.chartSeries = this.generateAllSeriesData();
      this.initLineChart();
    },
    
    // 更改图表类型
    changeChartType(type) {
      this.chartType = type;
      this.initLineChart();
    },
    
    // 获取图表标题
    getChartTitle() {
      const titles = {
        'basic': '时间序列折线图',
        'smooth': '平滑折线图',
        'area': '区域面积图',
        'step': '阶梯折线图'
      };
      return titles[this.chartType] || '折线图';
    },
    
    // 初始化折线图
    initLineChart() {
      if (!this.$refs.lineChart) return;
      
      // 销毁现有实例
      if (this.lineChartInstance) {
        this.lineChartInstance.dispose();
      }
      
      // 创建新实例
      this.lineChartInstance = echarts.init(this.$refs.lineChart);
      
      // 生成时间轴数据
      const times = Array.from({ length: this.dataPoints }, (_, i) => 
        this.getTimeLabel(i)
      );
      
      // 根据图表类型设置不同的配置
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: this.chartSeries.map(series => series.name),
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: this.chartType === 'area' ? false : true,
          data: times
        },
        yAxis: {
          type: 'value',
          name: '数值'
        },
        series: []
      };
      
      // 添加系列数据
      let idx = 0;
      const size = this.chartSeries.length;
      this.chartSeries.forEach(series => {
        idx++;
        let seriesConfig = {
          name: series.name,
          type: 'line',
          data: series.data,
          itemStyle: {
            color: series.color
          },
          step: (series.step ? idx == 1 ? 'start' : idx == size ? 'end' : series.step : null),
          symbol: series.symbol,
          symbolSize: series.symbolSize,
          emphasis: series.emphasis,
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [
              { type: 'average', name: '平均值' }
            ]
          }
        };
        
        // 根据图表类型调整配置
        switch (this.chartType) {
          case 'smooth':
            seriesConfig.smooth = true;
            break;
          case 'area':
            seriesConfig.areaStyle = {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: series.color + '80' },
                { offset: 1, color: series.color + '10' }
              ])
            };
            break;
          case 'step':
            seriesConfig.step = 'middle';
            seriesConfig.emphasis = {
              focus: 'series'
            };
            break;
        }
        
        option.series.push(seriesConfig);
      });
      
      // 设置配置项并渲染图表
      this.lineChartInstance.setOption(option);
      
      // 添加图表事件
      this.lineChartInstance.on('click', (params) => {
        console.log('图表点击:', params);
      });
    },
    
    // 窗口调整大小处理
    handleResize() {
      if (this.lineChartInstance) {
        this.lineChartInstance.resize();
      }
    }
  },
  
  mounted() {
    // 初始化数据
    this.chartSeries = this.generateAllSeriesData();
    
    // 使用$nextTick确保DOM已经渲染
    this.$nextTick(() => {
      this.initLineChart();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  
  beforeDestroy() {
    // 组件销毁时销毁图表实例
    if (this.lineChartInstance) {
      this.lineChartInstance.dispose();
      this.lineChartInstance = null;
    }
    
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  
  watch: {
    // 监听数据变化
    chartSeries: {
      handler() {
        this.$nextTick(() => {
          if (this.lineChartInstance) {
            this.initLineChart();
          }
        });
      },
      deep: true
    },
    
    // 监听激活标签变化
    activeTab() {
      // 可以在这里添加切换标签时的逻辑
    }
  }
}
</script>

<style scoped>
.container {
  margin: 0 auto;
  padding: 20px;
  /*
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  */
  max-width: 1400px;
  min-height: 100vh;
}

header {
  text-align: center;
  padding: 20px 0;
  margin-bottom: 30px;
}

h1 {
  font-size: 2.5rem;
  color: #3498db;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2rem;
  font-style: italic;
  color: #7f8c8d;
  max-width: 800px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.btn.active {
  background: #2c3e50;
}

.charts-container {
  display: grid;
  grid-template-columns: 1.5fr 1fr;
  gap: 25px;
  margin-top: 30px;
}

.chart-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 25px;
  transition: transform 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f1f1f1;
}

.chart-icon {
  width: 40px;
  height: 40px;
  background: #3498db;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 1.2rem;
}

.chart-title {
  font-size: 1.3rem;
  color: #2c3e50;
}

.chart-wrapper {
  width: 100%;
  height: 450px;
  margin-top: 15px;
}

.data-controls {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
}

.control-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

input[type="range"] {
  width: 100%;
}

.range-value {
  display: inline-block;
  min-width: 40px;
  text-align: center;
  background: #e9ecef;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: bold;
  margin-left: 10px;
}

.data-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.tab-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tab-btn:hover {
  background: #f0f0f0;
}

.tab-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
  display: block;
}

.data-table th, .data-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  position: sticky;
  top: 0;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.data-table tbody {
  display: block;
  max-height: 150px;
  overflow-y: auto;
}

.data-table thead, .data-table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

footer {
  text-align: center;
  margin-top: 40px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

@media (max-width: 968px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .chart-wrapper {
    height: 350px;
  }
  
  .controls {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 200px;
  }
  
  .data-tabs {
    justify-content: center;
  }
}
</style>